package com.jm.user.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.jm.common.exception.YyghException;
import com.jm.common.helper.JwtHelper;
import com.jm.common.result.Result;
import com.jm.common.result.ResultCodeEnum;
import com.jm.model.user.UserInfo;
import com.jm.user.service.UserInfoService;
import com.jm.user.utils.ConstantPropertiesUtil;
import com.jm.user.utils.HttpClientUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

//微信操作的接口
@Api(tags = "微信操作的接口")
@Controller
@RequestMapping("/api/ucenter/wx")
public class WeiXinApiController {
    @Resource
    private UserInfoService userInfoService;

    //1 生成微信二维码
    //返回二维码生成参数
    @ApiOperation(value = "返回二维码生成参数")
    @GetMapping("getLoginParam")
    @ResponseBody
    public Result getLoginParam() {
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("appid", ConstantPropertiesUtil.WX_OPEN_APP_ID);
            String redirectUri = URLEncoder.encode(ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL, "utf-8");
            map.put("redirectUri", redirectUri);
            map.put("scope", "snsapi_login");
            map.put("state", System.currentTimeMillis() + "");
            return Result.ok(map);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    //2 回调的方法，得到扫码人的信息
    //微信扫码后回调的方法
    @GetMapping("callback")
    public String callback(String code, String state) {
        //第一步：验证临时票据
        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(state)) {
            throw new YyghException(ResultCodeEnum.ILLEGAL_CALLBACK_REQUEST_ERROR);
        }
        //第二步：使用code、appid和appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/oauth2/access_token")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        try {
            //使用httpclient请求这个地址
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            //从返回字符串获取两个值，openid和access_token
            JSONObject jsonObject = JSONObject.parseObject(accessTokenInfo);
            String access_token = jsonObject.getString("access_token");
            String openid = jsonObject.getString("openid");

            //判断：根据openid查看数据库是否存在当前用户
            UserInfo userInfo = userInfoService.selectWxInfoOpenId(openid);

            if (userInfo == null) { //数据库不存在,进行添加
                //第三步：拿着access_token和openid请求微信地址，得到扫描人信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultInfo = HttpClientUtils.get(userInfoUrl);
                JSONObject resultUserInfoJson = JSONObject.parseObject(resultInfo);
                //解析用户信息
                //用户昵称
                String nickname = resultUserInfoJson.getString("nickname");
                //用户头像
                String headimgurl = resultUserInfoJson.getString("headimgurl");

                //第四步：将扫码人信息存入数据库
                userInfo = new UserInfo();
                userInfo.setNickName(nickname);
                userInfo.setOpenid(openid);
                userInfo.setStatus(1);
                userInfoService.save(userInfo);
            }

            //第五步：返回name和token字符串
            Map<String, String> map = new HashMap<>();
            String name = userInfo.getName();
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getNickName();
            }
            if (StringUtils.isEmpty(name)) {
                name = userInfo.getPhone();
            }
            map.put("name", name);
            //前端判断：如果opneid有值，需要绑定手机号；如果openid无值，不需要绑定手机号
            if (StringUtils.isEmpty(userInfo.getPhone())) {
                map.put("openid", userInfo.getOpenid());
            } else {
                map.put("openid", "");
            }
            String token = JwtHelper.createToken(userInfo.getId(), name);
            map.put("token", token);

            //跳转前端页面
            return "redirect:" + ConstantPropertiesUtil.YYGH_BASE_URL
                    + "/weixin/callback?token=" + map.get("token")
                    + "&openid=" + map.get("openid")
                    + "&name=" + URLEncoder.encode((String) map.get("name"));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
